package com.betterwood.dragon.core.common;

import lombok.Data;

import java.util.Objects;

@Data
public class JsonResult<T> {

    private T data;

    private Integer code;

    private String msg;

    public JsonResult() {
        this.code = StatusEnum.SUCCESS.getCode();
    }

    public JsonResult(T data) {
        this.data = data;
        this.code = StatusEnum.SUCCESS.getCode();
    }

    public JsonResult(T data, Integer code, String msg) {
        this.data = data;
        this.code = code;
        this.msg = msg;
    }

    public static <T> JsonResult<T> success() {
        JsonResult<T> apiResult = ofStatus(StatusEnum.SUCCESS);
        return apiResult;
    }

    public static <T> JsonResult<T> success(T data) {
        JsonResult<T> apiResult = ofStatus(StatusEnum.SUCCESS);
        apiResult.setData(data);
        return apiResult;
    }

    public static <T> JsonResult<T> fail(String message) {
        JsonResult<T> apiResult = ofStatus(StatusEnum.ERROR);
        apiResult.setMsg(message);
        return apiResult;
    }

    public static <T> JsonResult<T> fail(StatusEnum statusEnum, String message) {
        JsonResult<T> apiResult = ofStatus(statusEnum);
        apiResult.setMsg(message);
        return apiResult;
    }

    public static <T> JsonResult<T> ofStatus(StatusEnum status, T data) {
        return new JsonResult<>(data, status.getCode(), status.getMessage());
    }

    public static <T> JsonResult<T> ofStatus(StatusEnum status) {
        return ofStatus(status, null);
    }

    public static <T> JsonResult<T> ofException(Exception exception) {
        return fail(exception.getMessage());
    }

    public boolean hasSuccess() {
        return Objects.equals(this.code, StatusEnum.SUCCESS.getCode());
    }

    public boolean notSuccess() {
        return !hasSuccess();
    }
}